package com.netsdk.demo.customize;

import static com.netsdk.lib.Utils.getOsPrefix;

import java.io.File;
import java.text.SimpleDateFormat;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.enumeration.EM_STATEMANAGER_STATE;
import com.netsdk.lib.enumeration.NET_EM_CFG_OPERATE_TYPE;
import com.netsdk.lib.structure.NET_CASEABNORMAL_STATE_INFO;
import com.netsdk.lib.structure.NET_CFG_CONTROL_CASE_INFO;
import com.netsdk.lib.structure.NET_CFG_LAMP_EXTERNAL_DEVICE_INFO;
import com.netsdk.lib.structure.NET_IN_GET_STATEMANAGER_INFO;
import com.netsdk.lib.structure.NET_IN_SET_STATEMANAGER_INFO;
import com.netsdk.lib.structure.NET_LAMP_EXTERNAL_DEVICE_WIFIAP_INFO;
import com.netsdk.lib.structure.NET_OUT_GET_STATEMANAGER_INFO;
import com.netsdk.lib.structure.NET_OUT_SET_STATEMANAGER_INFO;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;

public class StateManagerDemo {
	// SDk对象初始化
	public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
	public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

	// 判断是否初始化
	private static boolean bInit = false;
	// 判断log是否打开
	private static boolean bLogOpen = false;
	// 设备信息
	private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
	// 登录句柄
	private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);

	// 回调函数需要是静态的，防止被系统回收
	// 断线回调
	private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
	// 重连回调
	private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

	// 编码格式
	public static String encode;

	static {
		String osPrefix = getOsPrefix();
		if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
			encode = "GBK";
		} else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
			encode = "UTF-8";
		}
	}

	/**
	 * 获取当前时间
	 */
	public static String GetDate() {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
	}

	/**
	 * 初始化SDK库
	 */
	public static boolean Init() {
		bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
		if (!bInit) {
			System.out.println("Initialize SDK failed");
			return false;
		}
		// 配置日志
		StateManagerDemo.enableLog();

		// 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
		netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

		// 设置登录超时时间和尝试次数，可选
		// 登录请求响应超时时间设置为3S
		int waitTime = 3000;
		// 登录时尝试建立链接 1 次
		int tryTimes = 1;
		netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
		// 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
		// 接口设置的登录设备超时时间和尝试次数意义相同,可选
		NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
		// 登录时尝试建立链接的超时时间
		netParam.nConnectTime = 10000;
		// 设置子连接的超时时间
		netParam.nGetConnInfoTime = 3000;
		netsdk.CLIENT_SetNetworkParam(netParam);
		return true;
	}

	/**
	 * 打开 sdk log
	 */
	private static void enableLog() {
		NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
		File path = new File("sdklog/");
		if (!path.exists())
			path.mkdir();

		// 这里的log保存地址依据实际情况自己调整
		String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
		setLog.nPrintStrategy = 0;
		setLog.bSetFilePath = 1;
		System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
		System.out.println(logPath);
		setLog.bSetPrintStrategy = 1;
		bLogOpen = netsdk.CLIENT_LogOpen(setLog);
		if (!bLogOpen)
			System.err.println("Failed to open NetSDK log");
	}

	/**
	 * 高安全登录
	 */
	public void loginWithHighLevel() {
		// 输入结构体参数
		NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
			{
				szIP = m_strIpAddr.getBytes();
				nPort = m_nPort;
				szUserName = m_strUser.getBytes();
				szPassword = m_strPassword.getBytes();
			}
		};
		// 输出结构体参数
		NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

		// 写入sdk
		m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
		if (m_hLoginHandle.longValue() == 0) {
			System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
					netsdk.CLIENT_GetLastError());
		} else {
			deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
			System.out.println("Login Success");
			System.out.println("Device Address：" + m_strIpAddr);
			System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
		}
	}

	/**
	 * 退出
	 */
	public void logOut() {
		if (m_hLoginHandle.longValue() != 0) {
			netsdk.CLIENT_Logout(m_hLoginHandle);
			System.out.println("LogOut Success");
		}
	}

	/**
	 * 清理sdk环境并退出
	 */
	public static void cleanAndExit() {
		if (bLogOpen) {
			netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
		}
		netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
		System.exit(0);
	}

	/**
	 * 控制智能机箱开关配置
	 */
	public void cfgControlCase() {
		// 先获取原先的默认配置
		NET_CFG_CONTROL_CASE_INFO info = new NET_CFG_CONTROL_CASE_INFO();
		Pointer pointer = new Memory(info.size());
		ToolKits.SetStructDataToPointer(info, pointer, 0);
		int emCfgOpType = NET_EM_CFG_OPERATE_TYPE.NET_EM_CFG_CONTROL_CASE; // 配置类型的枚举
		boolean ret1 = netsdk.CLIENT_GetConfig(m_hLoginHandle, emCfgOpType, -1, pointer, info.size(), 5000, null);
		if (!ret1) {
			System.err.println("获取控制智能机箱开关配置信息失败：" + ToolKits.getErrorCode());
			return;
		} else {
			System.out.println("获取控制智能机箱开关配置信息成功!");
			ToolKits.GetPointerData(pointer, info);
			System.out.println(" 交互机电源:" + info.bSwitcherPower); // 0 代表关 1代表开
			System.out.println(" ZIGBEE开关-使能开关:" + info.stuZigBee.bEnable);
			System.out.println(" ZIGBEE开关-节点号:" + new String(info.stuZigBee.szPanID));

			// 编辑配置并下发
			Pointer param = new Memory(info.size());
			ToolKits.SetStructDataToPointer(info, param, 0);
			boolean ret2 = netsdk.CLIENT_SetConfig(m_hLoginHandle, emCfgOpType, -1, param, info.size(), 5000,
					new IntByReference(0), null);
			if (!ret2) {
				System.err.println("下发控制智能机箱开关配置失败：" + ToolKits.getErrorCode());
				return;
			} else {
				System.out.println("下发控制智能机箱开关配置成功!");
			}
		}
	}

	/**
	 * 智慧灯杆项外设配置
	 */
	public void cfgLampExternalDevice() {
		// 先获取原先的默认配置
		NET_CFG_LAMP_EXTERNAL_DEVICE_INFO info = new NET_CFG_LAMP_EXTERNAL_DEVICE_INFO();
		Pointer pointer = new Memory(info.size());
		ToolKits.SetStructDataToPointer(info, pointer, 0);
		int emCfgOpType = NET_EM_CFG_OPERATE_TYPE.NET_EM_CFG_LAMP_EXTERNAL_DEVICE; // 配置类型的枚举
		boolean ret1 = netsdk.CLIENT_GetConfig(m_hLoginHandle, emCfgOpType, -1, pointer, info.size(), 5000, null);
		if (!ret1) {
			System.err.println("获取智慧灯杆项外设配置 信息失败：" + ToolKits.getErrorCode());
			return;
		} else {
			System.out.println("获取智慧灯杆项外设配置 信息成功!");
			ToolKits.GetPointerData(pointer, info);
			System.out.println(" 照明灯设备数量:" + info.nLightNum);
			System.out.println(" WifiAp设备数量:" + info.nWifiApNum);
			NET_LAMP_EXTERNAL_DEVICE_WIFIAP_INFO[] stuWifiAp = info.stuWifiAp;
			for (int i = 0; i < info.nWifiApNum; i++) {
				System.out.println(" [" + (i + 1) + "]WifiAp设备ID:" + new String(stuWifiAp[i].szId));
			}
			// 编辑配置并下发
			Pointer param = new Memory(info.size());
			ToolKits.SetStructDataToPointer(info, param, 0);
			boolean ret2 = netsdk.CLIENT_SetConfig(m_hLoginHandle, emCfgOpType, -1, param, info.size(), 5000,
					new IntByReference(0), null);
			if (!ret2) {
				System.err.println("下发智慧灯杆项外设配置 失败：" + ToolKits.getErrorCode());
				return;
			} else {
				System.out.println("下发智慧灯杆项外设配置 成功!");
			}
		}

	}

	/**
	 * 获取状态信息接口
	 */
	public NET_CASEABNORMAL_STATE_INFO getStateManager() {
		// 入参
		NET_IN_GET_STATEMANAGER_INFO pIn = new NET_IN_GET_STATEMANAGER_INFO();
		pIn.emState = EM_STATEMANAGER_STATE.EM_STATEMANAGER_STATE_CASEABNORMAL.getValue(); // 智能终端箱的异常状态,对应结构体NET_CASEABNORMAL_STATE_INFO
		pIn.write();
		// 出参
		NET_OUT_GET_STATEMANAGER_INFO pOut = new NET_OUT_GET_STATEMANAGER_INFO();
		NET_CASEABNORMAL_STATE_INFO info = new NET_CASEABNORMAL_STATE_INFO(); // emState不同，申请不同结构体的内存
		pOut.pStateInfo = new Memory(info.size());
		pOut.pStateInfo.clear(info.size());	
		pOut.write();

		boolean flg = netsdk.CLIENT_GetStateManager(m_hLoginHandle, pIn.getPointer(), pOut.getPointer(), 3000);
		if (!flg) {
			System.err.println("CLIENT_GetStateManager fail:" + ToolKits.getErrorCode());
		} else {
			System.out.println("CLIENT_GetStateManager success");
			pIn.read();
			pOut.read();
			ToolKits.GetPointerData(pOut.pStateInfo, info);
			//输入电压状态对应取值及含义：过压：1 <<0欠压：1 <<1过流：1 <<2漏电：1 <<3断电：1<<4, 可以组合，比如过压+欠压：11
			System.out.println(" 输入电压状态:"+new String(info.szInV));
			System.out.println(" 4G网络状态"+new String(info.szMobileNetwork));
			System.out.println(" 输出电压状态-DC12v1状态"+new String(info.stuOutV.szDc12v1));
			System.out.println(" 输出电压状态-DC12v2状态"+new String(info.stuOutV.szDc12v2));
		}
		return info;
	}

	/**
	 * 设置状态信息接口
	 */
	public void setStateManager() {
		// 获取状态信息
		NET_CASEABNORMAL_STATE_INFO info1 = getStateManager();
		// 入参
		NET_IN_SET_STATEMANAGER_INFO pIn = new NET_IN_SET_STATEMANAGER_INFO();
		pIn.emState = EM_STATEMANAGER_STATE.EM_STATEMANAGER_STATE_CASEABNORMAL.getValue(); // 智能终端箱的异常状态, 对应结构体NET_CASEABNORMAL_STATE_INFO
		// 参数赋值时注意字节对齐 System.arraycopy("01"szWater.getBytes(), 0, pIn.szWater, 0, "01".getBytes().length);
		NET_CASEABNORMAL_STATE_INFO info = info1;
		pIn.pStateInfo = new Memory(info.size());
		pIn.pStateInfo.clear(info.size());
		ToolKits.SetStructDataToPointer(info, pIn.pStateInfo, 0);
		pIn.write();
		// 出参
		NET_OUT_SET_STATEMANAGER_INFO pOut = new NET_OUT_SET_STATEMANAGER_INFO();
		pOut.write();

		boolean flg = netsdk.CLIENT_SetStateManager(m_hLoginHandle, pIn.getPointer(), pOut.getPointer(), 3000);
		if (!flg) {
			System.err.println("CLIENT_SetStateManager fail:" + ToolKits.getErrorCode());
		} else {
			System.out.println("CLIENT_SetStateManager success");
			pIn.read();
			pOut.read();
		}		
	}

	/******************************** 测试控制台 ***************************************/

	// 配置登陆地址，端口，用户名，密码
	private String m_strIpAddr = "172.6.103.96";
	private int m_nPort = 37777;
	private String m_strUser = "admin";
	private String m_strPassword = "admin123";

	public static void main(String[] args) {
		StateManagerDemo demo = new StateManagerDemo();
		demo.InitTest();
		demo.RunTest();
		demo.EndTest();

	}

	/**
	 * 初始化测试
	 */
	public void InitTest() {
		StateManagerDemo.Init();
		this.loginWithHighLevel();
	}

	/**
	 * 加载测试内容
	 */
	public void RunTest() {
		CaseMenu menu = new CaseMenu();
		menu.addItem(new CaseMenu.Item(this, "控制智能机箱开关配置", "cfgControlCase"));
		menu.addItem(new CaseMenu.Item(this, "智慧灯杆项外设配置", "cfgLampExternalDevice"));

		menu.addItem(new CaseMenu.Item(this, "获取状态信息接口", "getStateManager"));
		menu.addItem(new CaseMenu.Item(this, "设置状态信息接口", "setStateManager"));
		menu.run();
	}

	/**
	 * 结束测试
	 */
	public void EndTest() {
		System.out.println("End Test");
		this.logOut(); // 登出设备
		System.out.println("See You...");
		StateManagerDemo.cleanAndExit(); // 清理资源并退出
	}
	/******************************** 结束 ***************************************/

}
